package com.mpolicy.dbfile.common.utils;

import com.lowagie.text.Font;
import com.lowagie.text.*;
import com.lowagie.text.rtf.RtfWriter2;
import com.mpolicy.dbfile.common.constants.ExportConstants;
import com.mpolicy.dbfile.system.domain.TableFileds;
import com.mpolicy.dbfile.system.domain.Tables;
import com.mpolicy.dbfile.system.mapper.TableMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.awt.*;
import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * <p> 创建word文档 </p>
 *
 * @author : zhaoqiuyue
 * @description : 步骤:
 *                  1、建立文档
 *                  2、创建一个书写器
 *                  3、打开文档
 *                  4、向文档中写入数据
 *                  5、关闭文档
 * @date : 2019/11/8 15:45
 */
@Service
public class TableToWordUtil {

    @Autowired
    TableMapper tableMapper;

    /**
     * 生成word文档
     *
     * @param tables：该数据库下所有表信息
     * @param fileName：生成文件地址
     * @param title:文件内容标题
     * @return: void
     */
    public File toWord(List<Tables> tables, String fileName, String dbName, String title) {
        Document document = new Document(PageSize.A4);
        try {
            // 创建文件夹
            File dir = new File(ExportConstants.FILE_PATH);
            dir.mkdirs();

            // 创建文件
            File file = new File(fileName);
            if (file.exists() && file.isFile()) {
                file.delete();
            }
            file.createNewFile();

            // 写入文件信息
            RtfWriter2.getInstance(document, new FileOutputStream(fileName));
            document.open();
            // 1. 标题
            Paragraph ph = new Paragraph();
            Font f = new Font();
            Paragraph p = new Paragraph(title, new Font(Font.NORMAL, 24, Font.BOLD, new Color(0, 0, 0)));
            p.setAlignment(Element.ALIGN_CENTER);
            document.add(p);
            ph.setFont(f);
            // 2. 修订历史
            addHis(document);
            // 3. 数据库简介
            addDesc(document, dbName, tables, "一、数据库简介");
            // 4. 数据库概览
            addTable(document, tables, "二、数据库概览");
            // 5. 数据库详情
            addTableContent(document, tables, "三、数据库详情");
            document.close();
            return file;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 添加修订历史
     * @param document
     * @throws Exception
     */
    private void addHis(Document document) throws Exception {
        Paragraph p = new Paragraph("修订历史", new Font(Font.NORMAL, 18, Font.BOLD, new Color(0, 0, 0)));
        p.setAlignment(Element.ALIGN_CENTER);
        document.add(p);
        Table table = new Table(3);
        table.setWidth(90);
        table.setWidths(new int[]{100, 100 ,150});
        //添加表头的元素，并设置表头背景的颜色
        Color chade = new Color(176, 196, 222);
        addTableTitle(table, "修订者", chade);
        addTableTitle(table, "修订时间", chade);
        addTableTitle(table, "备注", chade);
        addTableContent(table, "自定义");
        addTableContent(table, new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
        addTableContent(table, "初始文档编写");
        addTableContent(table, "");
        addTableContent(table, "");
        addTableContent(table, "");
        addTableContent(table, "");
        addTableContent(table, "");
        addTableContent(table, "");
        document.add(table);
    }

    /**
     * 数据库简介
     * @param document
     * @param title
     */
    private void addDesc(Document document, String dbName, List<Tables> tables, String title) throws Exception {
        addTitle(document, title);
        addContent(document, "数据库名称：   "+dbName);
        long tableQty = tables.stream().filter(item -> item.getType().equalsIgnoreCase("BASE TABLE")).count();
        addContent(document, "数据表数量：   "+tableQty+"张");
        long viewQty = tables.stream().filter(item -> item.getType().equalsIgnoreCase("VIEW")).count();
        addContent(document, "视图数量：   "+viewQty+"张");
    }

    /**
     * 数据库概览
     * @param document
     * @param tables
     * @param title
     * @throws Exception
     */
    private void addTable(Document document, List<Tables> tables, String title) throws Exception {
        addTitle(document, title);
        Table table = new Table(3);
        table.setWidths(new int[]{30, 100, 140});
//        table.setAlignment(Element.ALIGN_LEFT);
        table.setBorderWidth(1);
        table.setPadding(4);
        table.setWidth(90);
        //添加表头的元素，并设置表头背景的颜色
        Color chade = new Color(176, 196, 222);

        addTableTitle(table, "编号", chade);
        addTableTitle(table, "表名", chade);
        addTableTitle(table, "注释", chade);

        for (int i = 0; i < tables.size(); i++) {
            String table_name = tables.get(i).getName();
            String table_comment = tables.get(i).getComment();
            addTableContent(table, (i + 1) + "");
            addTableContent(table, table_name, Element.ALIGN_LEFT);
            addTableContent(table, table_comment, Element.ALIGN_LEFT);
        }
        document.add(table);
    }

    /**
     * 插入表格内容
     * @param document
     * @param tables
     */
    private void addTableContent(Document document, List<Tables> tables, String title) throws Exception {
        addTitle(document, title);
        for (int i = 0; i < tables.size(); i++) {
            String table_name = tables.get(i).getName();
            String table_comment = tables.get(i).getComment();
            List<TableFileds> fileds = tableMapper.getTableInfo(tables.get(i).getName());
            Table table = new Table(6);
            table.setWidth(90);
            table.setWidths(new int[]{60, 130, 100, 75, 75, 150});
            document.add(new Paragraph(""));
//            table.setAlignment(Element.ALIGN_LEFT);
            table.setBorderWidth(1);
            table.setPadding(4);

            //添加表头的元素，并设置表头背景的颜色
            Color chade = new Color(176, 196, 222);

            addTableTitle(table, "编号", chade);
            addTableTitle(table, "字段名", chade);
            addTableTitle(table, "类型", chade);
            addTableTitle(table, "是否非空", chade);
            addTableTitle(table, "是否主键", chade);
            addTableTitle(table, "注释", chade);

            table.endHeaders();

            // 表格的主体
            for (int k = 0; k < fileds.size(); k++) {
                addTableContent(table, (k + 1) + "");
                addTableContent(table, fileds.get(k).getField(), Element.ALIGN_LEFT);
                addTableContent(table, fileds.get(k).getType(), Element.ALIGN_LEFT);
                addTableContent(table, fileds.get(k).getNull().equals("YES") ? "否" : "是");
                addTableContent(table, fileds.get(k).getKey().equals("PRI") ? "是" : "否");
                addTableContent(table, fileds.get(k).getComment(), Element.ALIGN_LEFT);
            }
            String nameAppend = tables.get(0).getType().equalsIgnoreCase("view")?". 视图名称:":". 表名称:";
            addContent(document, (i+1) + nameAppend + table_name + "（" + table_comment + "）");
            //生成表格
            document.add(table);
        }
    }

    /**
     * 新增标题
     * @param document
     * @param title
     */
    private void addTitle(Document document, String title) throws DocumentException {
        document.add(new Paragraph());
        Paragraph contentTitle = new Paragraph(title, new Font(Font.NORMAL, 16, Font.BOLD, new Color(0, 0, 0)));
        document.add(contentTitle);
    }

    private void addContent(Document document, String content) throws DocumentException {
        Paragraph contentPh = new Paragraph(content);
        contentPh.setIndentationLeft(24);
        document.add(contentPh);
    }

    /**
     * 添加表头到表格
     *
     * @param table
     * @param content
     * @param chade
     */
    private void addTableTitle(Table table, String content, Color chade) {
        Cell cell = new Cell(content);
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell.setBackgroundColor(chade);
        table.addCell(cell);
    }

    /**
     * 添加内容到表格
     *
     * @param table
     * @param content
     */
    private void addTableContent(Table table, String content) {
        Cell cell = new Cell(content);
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        table.addCell(cell);
    }

    /**
     * 添加内容到表格
     *
     * @param table
     * @param content
     */
    private void addTableContent(Table table, String content, int element) {
        Cell cell = new Cell(content);
        cell.setHorizontalAlignment(element);
        table.addCell(cell);
    }

}
